﻿/*----------------------------------------------------------------
 * 版权所有 (c) 2025 HaiTangYunchi  保留所有权利
 * CLR版本：4.0.30319.42000
 * 公司名称：
 * 命名空间：SalaryCalculator.Views
 * 唯一标识：ba9deea2-a7cb-4efc-b9aa-8dceebf3e73c
 * 文件名：MainForm
 * 
 * 创建者：海棠云螭
 * 电子邮箱：haitangyunchi@126.com
 * 创建时间：2025/5/10 20:21:52
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SalaryCalculator
{
    public partial class MainForm : Form
    {
        private EmployeeRepository _employeeRepo;
        private WorkRecordRepository _workRecordRepo;
        private SettlementRecordRepository _settlementRecordRepo;

        private List<Employee> _employees;
        private Employee _selectedEmployee;
        private List<WorkRecord> _unsettledRecords;

        public MainForm()
        {
            InitializeComponent();

            // 初始化数据库
            DatabaseHelper.InitializeDatabase();

            // 初始化数据访问对象
            _employeeRepo = new EmployeeRepository();
            _workRecordRepo = new WorkRecordRepository();
            _settlementRecordRepo = new SettlementRecordRepository();

            // 初始化UI
            InitializeUI();

            // 加载数据
            LoadEmployees();
        }

        private void InitializeUI()
        {
            // 设置DataGridView样式
            dataGridViewRecords.AutoGenerateColumns = false;
            dataGridViewRecords.Columns.Add("WorkDate", "工作日期");
            dataGridViewRecords.Columns["WorkDate"].DataPropertyName = "WorkDate";
            dataGridViewRecords.Columns["WorkDate"].DefaultCellStyle.Format = "yyyy-MM-dd";

            dataGridViewRecords.Columns.Add("StartTime", "上班时间");
            dataGridViewRecords.Columns["StartTime"].DataPropertyName = "StartTime";
            dataGridViewRecords.Columns["StartTime"].DefaultCellStyle.Format = @"hh\:mm";

            dataGridViewRecords.Columns.Add("EndTime", "下班时间");
            dataGridViewRecords.Columns["EndTime"].DataPropertyName = "EndTime";
            dataGridViewRecords.Columns["EndTime"].DefaultCellStyle.Format = @"hh\:mm";

            dataGridViewRecords.Columns.Add("BreakMinutes", "休息(分钟)");
            dataGridViewRecords.Columns["BreakMinutes"].DataPropertyName = "BreakMinutes";

            dataGridViewRecords.Columns.Add("WorkHours", "工时(小时)");
            dataGridViewRecords.Columns["WorkHours"].DataPropertyName = "WorkHours";
            dataGridViewRecords.Columns["WorkHours"].DefaultCellStyle.Format = "N2";

            // 设置ComboBox样式
            //comboBoxEmployees.DropDownStyle = ComboBoxStyle.DropDownList;

            // 设置按钮样式
            btnAddRecord.BackColor = Color.LightGreen;
            btnSettle.BackColor = Color.LightSkyBlue;
            btnViewHistory.BackColor = Color.LightGoldenrodYellow;
            btnManageEmployees.BackColor = Color.LightGray;

            dataGridViewRecords.CellDoubleClick += DataGridViewRecords_CellDoubleClick;
            dataGridViewRecords.ReadOnly = true; // 确保DataGridView是只读的
            // 设置标签样式
            // lblTotalHours.Font = new Font(Font, FontStyle.Bold);
            // lblTotalAmount.Font = new Font(Font, FontStyle.Bold);
            // lblTotalAmount.ForeColor = Color.DarkGreen;

            // 初始化结算范围控件
            //InitializeSettlementControls();
        }
        /**
        private void InitializeSettlementControls()
        {
            // 结算范围分组框
            groupBoxSettlement = new GroupBox
            {
                Location = new Point(300, 450),
                Size = new Size(472, 100),
                Text = "结算范围",
                TabStop = false
            };

            // 结算选项单选按钮
            radioButtonSelectedRecords = new RadioButton
            {
                Location = new Point(10, 20),
                Size = new Size(85, 17),
                Text = "选中记录",
                Checked = true
            };

            radioButtonByDateRange = new RadioButton
            {
                Location = new Point(10, 45),
                Size = new Size(85, 17),
                Text = "按日期范围"
            };

            radioButtonByMonth = new RadioButton
            {
                Location = new Point(10, 70),
                Size = new Size(61, 17),
                Text = "按月份"
            };

            // 日期范围选择器
            dateTimePickerStart = new DateTimePicker
            {
                Location = new Point(120, 45),
                Size = new Size(100, 20),
                Format = DateTimePickerFormat.Short,
                Enabled = false
            };

            dateTimePickerEnd = new DateTimePicker
            {
                Location = new Point(240, 45),
                Size = new Size(100, 20),
                Format = DateTimePickerFormat.Short,
                Enabled = false
            };

            // 月份选择
            comboBoxMonth = new ComboBox
            {
                Location = new Point(120, 70),
                Size = new Size(100, 21),
                Enabled = false
            };
            comboBoxMonth.Items.AddRange(Enumerable.Range(1, 12).Select(m => $"{m}月").ToArray());

            // 年份选择
            comboBoxYear = new ComboBox
            {
                Location = new Point(240, 70),
                Size = new Size(100, 21),
                Enabled = false
            };
            comboBoxYear.Items.AddRange(Enumerable.Range(DateTime.Now.Year - 5, 7).Cast<object>().ToArray());
            comboBoxYear.SelectedItem = DateTime.Now.Year;

            // 标签
            var labelTo = new Label
            {
                Location = new Point(225, 50),
                Size = new Size(13, 13),
                Text = "至"
            };

            // 添加控件到分组框
            groupBoxSettlement.Controls.AddRange(new Control[]
            {
                radioButtonSelectedRecords,
                radioButtonByDateRange,
                radioButtonByMonth,
                dateTimePickerStart,
                dateTimePickerEnd,
                labelTo,
                comboBoxMonth,
                comboBoxYear
            });

            // 添加分组框到窗体
            Controls.Add(groupBoxSettlement);

            // 事件绑定
            radioButtonSelectedRecords.CheckedChanged += SettlementOption_CheckedChanged;
            radioButtonByDateRange.CheckedChanged += SettlementOption_CheckedChanged;
            radioButtonByMonth.CheckedChanged += SettlementOption_CheckedChanged;
        }
        **/
       
        private void LoadEmployees()
        {
            _employees = _employeeRepo.GetAllEmployees();
            comboBoxEmployees.DataSource = _employees;
            comboBoxEmployees.DisplayMember = "Name";

            if (_employees.Count > 0)
            {
                _selectedEmployee = _employees[0];
                comboBoxEmployees.SelectedIndex = 0;
                LoadUnsettledRecords();
            }
            else
            {
                _selectedEmployee = null;
                dataGridViewRecords.DataSource = null;
                lblTotalHours.Text = "总工时: 0.00 小时";
                lblTotalAmount.Text = "总金额: ¥ 0.00";
            }
        }
        /// <summary>
        /// 处理DataGridView单元格双击事件
        /// </summary>
        private void DataGridViewRecords_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            // 确保点击的是有效行而不是标题行
            if (e.RowIndex < 0 || _selectedEmployee == null) return;

            // 获取选中的工作记录
            var selectedRecord = _unsettledRecords[e.RowIndex];

            // 创建并显示编辑表单
            var editForm = new EditWorkRecordForm(_selectedEmployee, selectedRecord);

            if (editForm.ShowDialog() == DialogResult.OK)
            {
                // 更新工作记录
                selectedRecord.WorkDate = editForm.WorkDate;
                selectedRecord.StartTime = editForm.StartTime;
                selectedRecord.EndTime = editForm.EndTime;
                selectedRecord.BreakMinutes = editForm.BreakMinutes;

                // 注意：这里不需要手动计算工时，因为WorkHours是计算属性
                // 会自动根据新的时间值重新计算

                // 更新数据库
                _workRecordRepo.UpdateWorkRecord(selectedRecord);

                // 刷新显示
                LoadUnsettledRecords();

                MessageBox.Show("记录已更新", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void LoadUnsettledRecords()
        {
            if (_selectedEmployee == null) return;

            _unsettledRecords = _workRecordRepo.GetUnsettledRecords(_selectedEmployee.Id);
            dataGridViewRecords.DataSource = _unsettledRecords;

            // 计算总工时和总金额
            double totalHours = _unsettledRecords.Sum(r => r.WorkHours);
            decimal totalAmount = (decimal)totalHours * _selectedEmployee.HourlyRate;

            lblTotalHours.Text = $"总工时: {totalHours:N2} 小时";
            lblTotalAmount.Text = $"总金额: ¥ {totalAmount:N2}";
        }

        private void comboBoxEmployees_SelectedIndexChanged(object sender, EventArgs e)
        {
            _selectedEmployee = comboBoxEmployees.SelectedItem as Employee;
            LoadUnsettledRecords();
        }

        private void btnAddRecord_Click(object sender, EventArgs e)
        {
            if (_selectedEmployee == null)
            {
                MessageBox.Show("请先选择员工", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var addForm = new AddWorkRecordForm(_selectedEmployee);
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                var record = new WorkRecord
                {
                    EmployeeId = _selectedEmployee.Id,
                    WorkDate = addForm.WorkDate,
                    StartTime = addForm.StartTime,
                    EndTime = addForm.EndTime,
                    BreakMinutes = addForm.BreakMinutes
                };

                _workRecordRepo.AddWorkRecord(record);
                LoadUnsettledRecords();
            }
        }

        private void SettlementOption_CheckedChanged(object sender, EventArgs e)
        {
            dateTimePickerStart.Enabled = radioButtonByDateRange.Checked;
            dateTimePickerEnd.Enabled = radioButtonByDateRange.Checked;
            comboBoxMonth.Enabled = radioButtonByMonth.Checked;
            comboBoxYear.Enabled = radioButtonByMonth.Checked;

            // 初始化日期范围
            if (radioButtonByDateRange.Checked)
            {
                dateTimePickerStart.Value = DateTime.Today.AddDays(-30);
                dateTimePickerEnd.Value = DateTime.Today;
            }

            // 初始化月份选择
            if (radioButtonByMonth.Checked && comboBoxYear.Items.Count == 0)
            {
                // 清空现有项
                comboBoxYear.Items.Clear();

                // 添加去年、今年、明年（int 类型）
                int currentYear = DateTime.Now.Year;
                comboBoxYear.Items.Add(currentYear - 1); // 去年
                comboBoxYear.Items.Add(currentYear);     // 今年
                comboBoxYear.SelectedItem = currentYear;
                comboBoxMonth.SelectedIndex = DateTime.Now.Month - 1;
            }
        }

        private void btnSettle_Click(object sender, EventArgs e)
        {
            if (_selectedEmployee == null)
            {
                MessageBox.Show("请先选择员工", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            List<WorkRecord> recordsToSettle;
            DateTime startDate, endDate;
            string settlementTitle;

            if (radioButtonSelectedRecords.Checked)
            {
                // 结算所有记录
                recordsToSettle = _unsettledRecords;
                if (recordsToSettle.Count == 0)
                {
                    MessageBox.Show($"【{_selectedEmployee.Name}】 名下没有未结算的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                startDate = recordsToSettle.Min(r => r.WorkDate);
                endDate = recordsToSettle.Max(r => r.WorkDate);
                settlementTitle = $"结算 【{_selectedEmployee.Name}】 的记录";
            }
            else if (radioButtonByDateRange.Checked)
            {
                // 按日期范围结算
                startDate = dateTimePickerStart.Value.Date;
                endDate = dateTimePickerEnd.Value.Date;

                if (startDate > endDate)
                {
                    MessageBox.Show("开始日期不能晚于结束日期", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                recordsToSettle = _workRecordRepo.GetRecordsByDateRange(_selectedEmployee.Id, startDate, endDate)
                    .Where(r => !r.IsSettled).ToList();

                settlementTitle = $"结算 【{_selectedEmployee.Name}】 {startDate:yyyy-MM-dd} 至 {endDate:yyyy-MM-dd} 的记录";
            }
            else if (radioButtonByMonth.Checked)
            {
                // 按月份结算
                int year = (int)comboBoxYear.SelectedItem;
                int month = comboBoxMonth.SelectedIndex + 1;

                startDate = new DateTime(year, month, 1);
                endDate = startDate.AddMonths(1).AddDays(-1);

                recordsToSettle = _workRecordRepo.GetRecordsByDateRange(_selectedEmployee.Id, startDate, endDate)
                    .Where(r => !r.IsSettled).ToList();

                settlementTitle = $"结算 【{_selectedEmployee.Name}】 {year}年{month}月的记录";
            }
            else
            {
                return;
            }

            if (recordsToSettle.Count == 0)
            {
                MessageBox.Show($"选定日期范围内没有未结算的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 计算总工时和总金额
            double totalHours = recordsToSettle.Sum(r => r.WorkHours);
            decimal totalAmount = (decimal)totalHours * _selectedEmployee.HourlyRate;

            var confirmResult = MessageBox.Show(
                $"{settlementTitle}\n\n" +
                $"总工时: {totalHours:N2} 小时\n" +
                $"小时工资: ¥{_selectedEmployee.HourlyRate:N2}\n" +
                $"总金额: ¥{totalAmount:N2}",
                "确认结算",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (confirmResult == DialogResult.Yes)
            {
                // 添加结算记录
                _settlementRecordRepo.AddSettlementRecord(new SettlementRecord
                {
                    EmployeeId = _selectedEmployee.Id,
                    StartDate = startDate,
                    EndDate = endDate,
                    SettlementDate = DateTime.Today,
                    TotalHours = totalHours,
                    TotalAmount = totalAmount
                });

                // 标记工作记录为已结算
                _workRecordRepo.MarkRecordsAsSettled(recordsToSettle.Select(r => r.Id).ToList());

                LoadUnsettledRecords();
                MessageBox.Show($"结算成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnViewHistory_Click(object sender, EventArgs e)
        {
            var historyForm = new SettlementHistoryForm();
            historyForm.ShowDialog();
        }

        private void btnManageEmployees_Click(object sender, EventArgs e)
        {
            var manageForm = new ManageEmployeesForm();
            if (manageForm.ShowDialog() == DialogResult.OK)
            {
                LoadEmployees();
            }
        }
    }
}
